package cn.com.nthotline.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.GridView;
import android.widget.Toast;

public class CommonUtil {

	/**
	 * 发送消息
	 * */
	public static void sendMessage(Handler handler, int what) {

		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
		msg = null;
	}

	/**
	 * 发送消息+arg1
	 * */
	public static void sendMessage(Handler handler, int what, int arg1) {

		Message msg = new Message();
		msg.what = what;
		msg.arg1 = arg1;
		handler.sendMessage(msg);
		msg = null;

	}

	/**
	 * 发送消息+obj
	 * */
	public static void sendMessage(Handler handler, int what, Object obj) {

		Message msg = new Message();
		msg.what = what;
		msg.obj = obj;
		handler.sendMessage(msg);
		msg = null;

	}

	public static void sendMessage(Handler handler, int what, String key,
			List<Object> list) {
		Message msg = new Message();
		msg.what = what;
		msg.getData().putSerializable(key, list.toArray());
		handler.sendMessage(msg);
		msg = null;
	}

	public static void showShortToast(Context context, String text) {
		Toast.makeText(context, text, 0).show();
	}

	public static void showLongToast(Context context, String text) {
		Toast.makeText(context, text, 1).show();
	}

	public static String formatProfeName(String value) {
		String name = "";
		switch (Integer.valueOf(value)) {

		case 1:
			name = "初中";
			break;
		case 2:
			name = "高中";
			break;
		case 3:
			name = "职高/技校";
			break;
		case 4:
			name = "中专";
			break;
		case 5:
			name = "大专";
			break;
		case 6:
			name = "大学本科";
			break;
		case 7:
			name = "硕士";
			break;
		case 8:
			name = "博士";
			break;

		default:
			break;
		}
		return name;
	}

	public static String formatJobType(String value) {
		String name = "";
		switch (Integer.valueOf(value)) {

		case 1:
			name = "全职";
			break;
		case 2:
			name = "兼职";
			break;
		case 3:
			name = "全/兼职";
			break;
		default:
			break;
		}
		return name;
	}

	public static String now() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(new Date());
	}

	public static String filterHtml(String text) {
		return text.replaceAll("\\<.*?>", "\r\n").replaceAll("&nbsp", "");
	}
	public static String filterHtml1(String text) {
		return text.replaceAll("\\<.*?>", "").replaceAll("&nbsp;", "");
	}
	public static String filterHtmlNotice(String text) {
		return text.replaceAll("&#160;", "").replaceAll("\\<.*?>", "\n").replaceAll("&nbsp;", "");
	}
	public static String formatAddrStr(String str) {
		return str.replaceAll("\\*", " ");
	}

	public static String formatProfStr(String str) {
		return str.replaceAll("\\*", "-");
	}

	public static String postUrl(ArrayList<NameValuePair> nameValuePairs,
			String url, String encode) {
		// String result = "";
		String tmp = "";
		InputStream is = null;
		try {
			// nameValuePairs.add(new BasicNameValuePair("type",
			// "getbaseinfo"));

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			return "error";
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, encode));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();

			tmp = sb.toString();
		} catch (Exception e) {
			return "error";
		}

		// try{
		// JSONArray jArray = new JSONArray(tmp);
		// for(int i=0;i<jArray.length();i++){
		// JSONObject json_data = jArray.getJSONObject(i);
		// Iterator<?> keys=json_data.keys();
		// while(keys.hasNext()){
		// result += json_data.getString(keys.next().toString());
		// }
		// }
		// }catch(JSONException e){
		// return "The URL you post is wrong!";
		// }

		return tmp;
	}

	public static String formatStr(String str) {
		return str.substring(str.lastIndexOf("*") + 1, str.length());
	}

	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}

		return flag;
	}

	public static List<String> read(InputStream openRawResource) {
		StringBuilder stringBuilder = new StringBuilder();
		byte[] buffer = null;
		List<String> sqlList = new ArrayList<String>();
		try {
			while (openRawResource.available() > 0) {
				buffer = new byte[openRawResource.available()];
				openRawResource.read(buffer);
				String str = new String(buffer, "UTF-8");
				int semicolonIndex = str.indexOf(";");
				if (semicolonIndex > -1) {
					String[] parts = str.split(";");
					stringBuilder.append(parts[0]);
					sqlList.add(stringBuilder.toString().trim());
					stringBuilder.setLength(0);
					for (int index = 1; index < parts.length - 1; index++) {
						sqlList.add(parts[index]);
					}
					if (str.endsWith(";") && parts.length > 1) {
						sqlList.add(parts[parts.length - 1]);
					} else {
						stringBuilder.append(parts[parts.length - 1]);
					}
				} else {
					stringBuilder.append(str);
				}

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sqlList;
	}

	public static void copy(InputStream in, String dest, Context context)
			throws Exception {
		new File(context.getFilesDir().getParent() + "/DB").mkdirs();
		int len = 0;
		byte[] b = new byte[1024];
		OutputStream os = new FileOutputStream(new File(dest));
		while ((len = in.read(b)) != -1) {
			os.write(b, 0, len);
		}
		os.close();
		in.close();
	}

	public static Intent createShareIntent(String msg) {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_TEXT, msg);
		return Intent.createChooser(intent, "分享到...");
	}

	public static int getGridViewItemSize(Activity activity, GridView gridView,
			int numColums) {
		int screenWidth = activity.getWindowManager().getDefaultDisplay()
				.getWidth();
		int totalPadding = gridView.getPaddingLeft() * (numColums + 1);
		int itemSize = (screenWidth - totalPadding) / numColums;
		return itemSize;
	}

	/**
	 * 信息列表中显示的发布时间
	 * @param str
	 * @return
	 */
	public static String formatDate(String str) {
		long seconds = Long.valueOf(str);
		Timestamp time = new Timestamp(seconds * 1000L);
		SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm");
		return df.format(time);
	}
	public static String formatDate1(String str) {
		long seconds = Long.valueOf(str);
		Timestamp time = new Timestamp(seconds * 1000L);
		SimpleDateFormat df = new SimpleDateFormat("yy-MM-dd HH:mm");
		return df.format(time);
	}
	public static String formatYear(String str) {
		long seconds = Long.valueOf(str);
		Timestamp time = new Timestamp(seconds * 1000L);
		SimpleDateFormat df = new SimpleDateFormat("yy-MM-dd");
		return df.format(time);
	}
	public static int age(String birth){
		SimpleDateFormat df=new SimpleDateFormat("yyyy");
		int year=Integer.valueOf(df.format(new Date()));
		int bir=Integer.parseInt(birth);
		return year-bir;
	}
	public static Map<String, String> readAssert(Context context,
			String fileName) {
		Map<String, String> map = new HashMap<String, String>();
		ByteArrayOutputStream os = null;
		InputStream in = null;
		try {
			in = context.getAssets().open(fileName);
			int len = 0;
			byte[] buf = new byte[1024];
			os = new ByteArrayOutputStream();
			while ((len = in.read(buf)) != -1) {
				os.write(buf, 0, len);
			}
			String content = new String(os.toByteArray());
			String[] array=content.split("\r\n");
			for(int i=0,j=array.length;i<j;i++){
				String[] area=array[i].split("=");	
				for(int m=0,n=area.length;m<n;m++){
					map.put(area[0], area[1]);
				}
				System.out.println(area[0]+"="+area[1]);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
					os = null;
				}
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return map;
	}

	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}
}
